package com.fivec.javaproject.rpc;

import com.alibaba.fastjson.JSONObject;
import com.fivec.javaproject.Constants;
import com.fivec.javaproject.btcrpcentity.ChainInfo;
import com.fivec.javaproject.btcrpcentity.RpcChainInfo;
import com.fivec.javaproject.btcrpcentity.RpcDeserialization;
import com.fivec.javaproject.net.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangyizhu
 * @version "1.8.0_131"
 * @email 2641956765@qq.com
 * @desc:GetBlockChainInfo获取区块链当前状态
 * @Time 2021/12/16 11:24
 */
public class GetBlockChainInfo {
    public ChainInfo getBlockChainInfo(int id) {
        //准备rpc 请求的用户信息
        String author = Constants.BITCOIN_RPC_USER + ":" + Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();
        String authorBase64 = encoder.encodeToString(author.getBytes());
        //请求头的属性设置
        Map<String, String> header = new HashMap<>();
        header.put("ContentType", "application/json");
        header.put("Authorization", "Basic " + authorBase64);

        //准备rpc请求的数据
        Map<String, Object> body = new HashMap<>();
        body.put("id", id);
        body.put("method", "getblockchaininfo");
        body.put("params", null);
        body.put("json_rpc", "2.0");
        byte[] bodyBytes = JSONObject.toJSONBytes(body);

        //{"id":1001,"result":xxx,"error":null}
        String result = HttpUtils.post(
                Constants.BITCOIN_RPC_URL,
                header,
                bodyBytes);
        //反序列化，拿到result的值
        RpcChainInfo rpcChainInfo = JSONObject.parseObject(result,RpcChainInfo.class);
        return rpcChainInfo.getResult();
    }
}
